import { Component,ViewChild} from '@angular/core';
import { NavController,Slides,ToastController,LoadingController,AlertController} from 'ionic-angular';

import {AppContentService} from "../../providers/AppContentService";
import {BANNER_PATH} from "../../providers/Constants"
import {BaseUI} from "../../common/baseui";
import {SportDynamicService} from "../../providers/SportDynamicService";
import {USERFACE_PATH,SPORT_DYNAMIC_IMG_PATH} from "../../providers/Constants";
import {UserInfo} from "../../model/UserInfo";
import {StorageService} from "../../providers/StorageService";
import {CheckUtil} from "../../common/CheckUtil";
import { JPushService } from 'ionic2-jpush/dist';
import { Platform } from 'ionic-angular';
import {JmessageChenyu} from "jmessage-chenyu";

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers  : [JPushService]
})
export class HomePage extends BaseUI {
	@ViewChild(Slides) slides: Slides;
  // users: Array<{
  //   userface: string,
  //   username:string,
  //   pubtime:any,
  //   img:any,
  //   component: any,
  //   likeNum:any,
  //   commetNum:any,
  //   ago:any,
  // }>;
  pageSize:any=30;
  pageNum:any=1;
  errorMessage: any;
  banners: string[];
  bannerPath:any;
  sportDynamicList:any;
  lastNote:string;//初始化提示语
  isLoadEnd:boolean;
  userFacePath:string;
  sportDynamicImgPath:string
  constructor(
              public navCtrl: NavController,
              private appContService : AppContentService,
              public toastCtrl:ToastController,
              public loadingCtrl:LoadingController,
              public sportDynamicService:SportDynamicService,
              public storageService:StorageService,
              public checkUtil:CheckUtil,
              public alertCtrl:AlertController,
              private jPushPlugin: JPushService,//极光推送服务
              private platform: Platform,
              private jmessageChenyu:JmessageChenyu,
  ) {
    super();

    this.bannerPath = BANNER_PATH;
    this.userFacePath =USERFACE_PATH;
    this.sportDynamicImgPath = SPORT_DYNAMIC_IMG_PATH;


    // platform.ready().then( () =>{
    //
    //   this.jPushPlugin.openNotification()
    //     .subscribe( res => {
    //       console.log('收到推送');
    //       console.log(res)
    //     });
    //
    //   this.jPushPlugin.receiveNotification()
    //     .subscribe( res => {
    //       console.log('收到推送');
    //       console.log(res)
    //     });
    //
    //   this.jPushPlugin.receiveMessage()
    //     .subscribe( res => {
    //       console.log('收到推送');
    //       console.log(res)
    //     });
    //
    // })
  }

  // ngOnInit(){//页面加载完成后自己调用
  //   this.slides.pager = true;
  //   //参照官网这个属性表示轮播图能够循环
  //   this.slides.loop = true;
  //   setInterval(()=>{
  //       //1000:表示速度，true表示能够触发事件
  //       this.slides.slideNext(1000,true);
  //   },2000);
  // }
//解决自动播放的Slides调转到其他页面一定时间后（超过设置的播放时间），再回到此页面，自动播放失效
   //页面进入时启动自动播放
  // 进入的时候自动播放
  // ionViewWillEnter() {
  //   this.bannerPath = BANNER_PATH;
  //   this.getBannerList();
  //   this.slides.startAutoplay();
  //   console.log("页面载入");
  // }



  ionViewDidEnter(){
      this.getBannerList();
      if(this.slides){
        this.slides.startAutoplay();
      }
    this.pageNum=1;
    this.lastNote=null;//初始化提示语
    this.isLoadEnd=false;//初始化加载完成状态
    this.getSportDynamicList(this.pageNum);
    // this.jpushInit();
  }
// 离开的时候暂停

  ionViewDidLeave() {
    if(this.slides){
      this.slides.stopAutoplay();
    }

    console.log("页面退出");
  }

  //请求服务器资源
  getBannerList(){
     this.appContService.getBannerList().subscribe(
       res=>{
         console.log(res["msg"]);
         this.banners = res["data"];
       }, error => {
         this.errorMessage = error;
         // this.toastCtrl.create({message:"网络请求失败", duration: 4500,position:'middle'}).present();
         super.showToast(this.toastCtrl,"网络请求失败",'middle');
       });
  }

  //刷新
  doRefresh(refresher) {
    this.pageNum=1;
    this.lastNote=null;//初始化提示语
    this.isLoadEnd=false;//初始化加载完成状态
    setTimeout(() => {
      this.getSportDynamicList(1);
      refresher.complete();
    }, 2000);
  }

  //打开发布动态页面
  openPubSportDynamic(){
    this.navCtrl.push('PubSportDynamicPage');
  }

  //获取最新动态
  getSportDynamicList(pageNum){
    this.sportDynamicService.sportDynamicList(pageNum,this.pageSize).subscribe(res=>{
      this.sportDynamicList = res['data'];
      if(res["data"].length==0||res["data"]==""){
        // this.lastNote="没有更多的数据了";
        this.isLoadEnd=true;
      }
    })
  }

  //加载
  doInfinite(infiniteScroll) {
    console.log(this.isLoadEnd);
    if(this.isLoadEnd){
      infiniteScroll.complete();
      return null;//如果已经到底，就不再发送请求
    }
    setTimeout(() => {
      this.sportDynamicService.sportDynamicList(++this.pageNum,this.pageSize).subscribe(
        res=>{
          console.log("data:"+res["data"]);
          this.sportDynamicList=this.sportDynamicList.concat(res["data"]);
          if(res["data"].length==0||res["data"]==""){
            this.lastNote="没有更多的数据了";
            this.isLoadEnd=true;
          }
          console.log(this.sportDynamicList);
        });

      console.log('Async operation has ended');
      infiniteScroll.complete();
    }, 500);
  }
  //点赞
  doLike(sportDynamicId){
    if(!this.checkUtil.checkUserLogin()){
      super.showAlert(this.alertCtrl,null,"亲，你还未登录哟!去个人中心登录体验更多功能吧！",'确定');
      return false;
    }
    // if(this.isLoadEnd && this.pageNum>1){
    //   this.pageNum=this.pageNum-1;
    // }
    var userId = this.storageService.read<UserInfo>('UserInfo').id
    this.sportDynamicService.sportDynamicDoLike(userId,sportDynamicId).subscribe(res=>{
      this.getSportDynamicList(1);
    })
  }

  //评论
  openDetail(){
    super.showAlert(this.alertCtrl,null,'Sorry!该功能还未开放','确定')
  }


}
